/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package StringParser;

import model.Image;

/**
 *
 * @author RodriguesMoises
 */
public class StringToImage {
    public static Image parse(String string) {
       //"|Image{" + "indexInArray=" + indexInArray + ",| image=" + image + "}Image|";
        if(string.startsWith("|Image{") && string.endsWith("}Image|"))
        {
            Image image = new Image();
            int indexOfIndexInArray;
            indexOfIndexInArray = string.indexOf("indexInArray=") + "indexInArray=".length();
            String strIndex = string.substring(indexOfIndexInArray, string.indexOf(",| image="));
            image.setIndexInArray(Integer.parseInt(strIndex));
            
            int indexOfImage = string.indexOf("image=") + "image=".length();
            String stringArray = string.substring(indexOfImage, string.indexOf("]}Image|")+1);
            byte[] bytes = stringToBytes(stringArray);
            image.setImage(bytes);
            return image;
        }
        else
        {
            return null;
        }
    }
    
    private static byte[] stringToBytes(String string)
    {
        byte[] bytes = null;
        //System.out.println(string.length());
        if(string.length() % 3 == 0)
        {
            bytes = new byte[string.length()/3];
            for (int i = 0; i < bytes.length; i++) {
                bytes[i] = (byte)string.charAt(3*i + 1);
            }
        }
        return bytes;
    }
}
